package com.kuang.config;

import com.kuang.pojo.User;
import com.kuang.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的UserRealm 继承 AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService service;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了 授权doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//现在拿到User对象了
        //有了用户的对象我们就可以设置权限了
        info.addStringPermission(currentUser.getPerms());//设置当前用户的权限

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //连接真实的数据库
        User user = service.queryUserByName(userToken.getUsername());
        if(user==null){//如果的到的user是null说明没有这个人
            return null;//UnknownAccountException汇报这个异常
        }
        //密码认证你不用做shiro会做 我们直接调用下面这个方法 如果我们上面的到的user不是null这里直接拿user的pwd来判断就可以了
        return new SimpleAuthenticationInfo(user,user.getPwd(),"") ;
        //补充：密码可以加密:MD5 MD5盐值加密
    }
}
